package com.itheima.app.interceptor;

import com.itheima.app.exception.BusinessExcepiton;
import com.itheima.domain.db.Freeze;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.db.FreezeService;
import com.itheima.service.db.UserInfoService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

@Component
public class UserStateInterceptor implements HandlerInterceptor {

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private FreezeService freezeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Long userId = UserHolder.get().getId();
        UserInfo userInfo = userInfoService.findByUserId(userId);
        String status = userInfo.getUserStatus();

        //判断是冻结
        if (!Objects.equals(status,"1")){
            Freeze freeze = freezeService.findByUserId(userId);
            //判断是否为冻结登录
            Integer range = freeze.getFreezingRange();
            switch (range) {
                case 1:
                    throw new BusinessExcepiton("当前账户为冻结状态");
                case 2:
                    if (Objects.equals(request.getMethod(),"POST")){
                        throw new BusinessExcepiton("当前账户不能发言");
                    }
                case 3:
                    if (Objects.equals(request.getMethod(),"POST")){
                        throw new BusinessExcepiton("当前账户不能发动态");
                    }
            }
        }

        return true;
    }
}
